import { routerRedux } from 'dva/router';

import { queryLogin, queryInfo, modifyPwd, queryUnitList ,queryUnitById} from '@/services/user';

import { setAuth } from '@/utils/Auth';

export default {
	namespace: 'user',

	state: {
		unitList : {data:[]},
  },

	effects: {
		//选择单位
		*chooseUnit({ payload }, { call, put }){
			const response = yield call(queryUnitById, payload.id);
			// sessionStorage.clear();
			setAuth(response.token || '');

			const res = yield call(queryInfo);
			yield put({ type: 'setInfo', payload: res });
			yield put({ type: 'menu/queryMenu' });
			yield put(routerRedux.push('/home'));
		},
		//获取单位列表
		*queryUnitList(_, { call, put }) {
      const response = yield call(queryUnitList);
			yield put({ type: 'setUnitList', payload: response === '操作成功' ? [] : response });
		},
		*login({ payload }, { call, put }) {
			sessionStorage.clear();
			const response = yield call(queryLogin, payload);
			setAuth(response.token || '');
			//yield put(routerRedux.push('/home'));
		},
		*queryInfo(_, { call, put, select }) {
			const details = yield select((state) => state.user.details);

			if (!details) {
				const response = yield call(queryInfo);
				yield put({ type: 'setInfo', payload: response });
			}
		},
		*logout(_, { put }) {
			setAuth('');
			window.location.href = '/users/login'
			// yield put({ type: 'setInfo', payload: null });
			// yield put(routerRedux.push('/users/login'));
		},
		*modifyPwd({ payload }, { call, put }) {
			yield call(modifyPwd, payload);
		}
	},

	reducers: {
		setInfo(state, action) {
			return {
				...state,
				details: action.payload
			};
    },
    setUnitList(state, action) {
       return {
         ...state,
         unitList : action.payload
       };
		 },
	},

};
